﻿using System;
using System.Diagnostics;
using System.Globalization;

namespace PortableVersion.Core.FileSystem
{
    public enum FilePosition { Master, Slave }

    [DebuggerDisplay("{Path}", Name = "{Key}")]
    public class FileItem : IEquatable<FileItem>, IVersioningItem
    {
        public string Name
        {
            get { return System.IO.Path.GetFileName(Path); }
        }

        public string Path { get; set; }
        public DateTime ModifiedDate { get; set; }
        public DateTime CreatedDate { get; set; }
        public FilePosition Position { get; set; }
        public bool IsFolder { get; set; }

        DateTime IVersioningItem.ModifiedDate
        {
            get { return ModifiedDate; }
        }

        public string Key
        {
            get { return CreatedDate.ToString("yyMMddHHmmss"); }
        }

        public bool Equals(FileItem other)
        {
            return Path.Equals(other.Path);
        }

        public bool IsSameFile(FileItem other)
        {
            if (Position != FilePosition.Slave)
                throw new InvalidOperationException("IsSameFile can only be called on slave files.");
            return Key.Equals(other.Key);
        }

        public static FileItem CreateFrom(string key, string path, DateTime modiDate, bool isFolder, FilePosition position)
        {
            var crDate = DateTime.ParseExact(key, "yyMMddHHmmss", CultureInfo.InvariantCulture);
            return new FileItem
                       {
                           CreatedDate = crDate,
                           IsFolder = isFolder,
                           ModifiedDate = modiDate,
                           Path = path,
                           Position = position
                       };
        }
    }
}
